package shinesend.com.cn.anscyhandledemo;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by MyPC on 2016/11/22.
 * Handler的使用;
 */
public class SecondActivity extends Activity {
    private ImageView image;
    private final int DOWNLOAD_SUCCESS = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = (ImageView) findViewById(R.id.imageview);
    }
    //Handle 通信机制;
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {//信息可以封装成我们需要的额;
            super.handleMessage(msg);
            switch (msg.what){
                case DOWNLOAD_SUCCESS:
                    Bitmap btm = (Bitmap) msg.obj;
                    image.setImageBitmap(btm);
                    break;
            }
        }
    };
    public void click(View view) {
        final String link = "http://pic22.nipic.com/20120725/6573765_165852471000_2.jpg";//地址
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    URL url = new URL(link);
                    //开启url网络连接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    //设置方法
                    connection.setRequestMethod("GET");
                    //获取返回的参数
                    if (connection.getResponseCode()==HttpURLConnection.HTTP_OK){
                        //当连接成功的时候使用
                        //获取从网络上得到的流
                        InputStream is = connection.getInputStream();
                        Bitmap btm =  BitmapFactory.decodeStream(is);//将流转化为bitmap
                        Message msg = mHandler.obtainMessage();
                        msg.what = DOWNLOAD_SUCCESS;
                        msg.obj = btm;
                        mHandler.sendMessage(msg);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
